<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  showToast,
  showLoadingToast,
  showSuccessToast,
  closeToast,
} from "vant";
import QRCode from 'qrcode';

const route = useRoute();
const router = useRouter();

const orderData = ref<any>({});
const paymentStatus = ref("pending"); // pending, processing, success, failed
const resetTimer = ref<ReturnType<typeof setTimeout> | null>(null);
const qrCodeUrl = ref(""); // 新增：二维码URL
const showQrCode = ref(false); // 新增：是否显示二维码

// 返回上一页
const goBack = () => {
  router.back();
};

// 生成支付宝支付URL（示例）
const generateAlipayUrl = async (orderData: any) => {
  const params = {
    out_trade_no: orderData.orderId,
    total_amount: orderData.amount,
    subject: `订单支付-${orderData.orderId}`,
  };
  
  const paymentUrl = `https://openapi.alipaydev.com/gateway.do?${new URLSearchParams(params).toString()}`;
  
  // 生成二维码图片
  try {
    const qrCodeDataUrl = await QRCode.toDataURL(paymentUrl);
    return qrCodeDataUrl;
  } catch (error) {
    console.error('生成二维码失败:', error);
    // fallback 到在线服务
    return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(paymentUrl)}`;
  }
};

// 支付处理函数（删除第一个重复的函数，保留这个）
const processPayment = async () => {
  if (paymentStatus.value !== "pending") {
    return;
  }

  // 清除之前的重置定时器
  if (resetTimer.value) {
    clearTimeout(resetTimer.value);
    resetTimer.value = null;
  }

  paymentStatus.value = "processing";

  showLoadingToast({
    message: "正在跳转支付宝...",
    forbidClick: true,
    duration: 2000,
  });

  try {
    // 验证订单数据
    if (!orderData.value?.orderId || !orderData.value?.amount) {
      throw new Error("订单数据不完整");
    }

    if (orderData.value.amount <= 0) {
      throw new Error("订单金额异常");
    }

    // 生成支付宝支付链接和二维码
    const qrCodeImageUrl = await generateAlipayUrl(orderData.value);
    
    // 显示二维码
    qrCodeUrl.value = qrCodeImageUrl;
    showQrCode.value = true;
    
    closeToast();
    
    // 改为手动确认支付，而不是自动成功
    paymentStatus.value = "pending";
    
    showToast({
      message: "请完成支付后点击确认",
      duration: 3000
    });

  } catch (error) {
    closeToast();
    paymentStatus.value = "failed";
    console.error("支付失败:", error);

    const errorMessage =
      error instanceof Error && error.message
        ? error.message
        : "支付失败，请重试";

    showToast(errorMessage);

    // 支付失败后允许重新支付
    resetTimer.value = setTimeout(() => {
      if (paymentStatus.value === "failed") {
        paymentStatus.value = "pending";
      }
      resetTimer.value = null;
    }, 3000);
  }
};

// 添加手动确认支付按钮
const confirmPayment = () => {
  // 这里可以调用后端API查询支付状态
  // 或者让用户手动确认已完成支付
  handlePaymentSuccess();
};

// 处理支付成功
const handlePaymentSuccess = () => {
  paymentStatus.value = "success";
  showQrCode.value = false;
  
  // 清除订单缓存
  try {
    sessionStorage.removeItem("pendingOrder");
  } catch (storageError) {
    console.warn("清除订单缓存失败:", storageError);
  }

  // 清空购物车
  try {
    localStorage.removeItem("cartItems");
    console.log("购物车已清空");
  } catch (storageError) {
    console.warn("清空购物车失败:", storageError);
  }

  showSuccessToast({
    message: "支付成功！",
    duration: 2000,
  });

  // 延迟跳转
  setTimeout(() => {
    router.replace("/shop");
  }, 2000);
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (resetTimer.value) {
    clearTimeout(resetTimer.value);
  }
});

// 页面初始化
onMounted(() => {
  try {
    const orderId = route.query.orderId as string;

    if (orderId) {
      // 从sessionStorage获取订单数据
      const storedOrder = sessionStorage.getItem("pendingOrder");
      if (storedOrder) {
        const parsedOrder = JSON.parse(storedOrder);
        if (parsedOrder.orderId === orderId) {
          orderData.value = parsedOrder;
          return;
        }
      }
    }

    // 兼容旧的传参方式
    const queryOrderData = route.query.orderData as string;
    if (queryOrderData) {
      orderData.value = JSON.parse(queryOrderData);
      return;
    }

    throw new Error("未找到订单数据");
  } catch (error) {
    console.error("订单数据获取失败:", error);
    showToast("订单数据异常");
    router.back();
  }
});
</script>

<template>
  <div class="payment-container">
    <!-- 头部导航 -->
    <van-nav-bar
      title="支付订单"
      left-arrow
      @click-left="goBack"
      class="payment-header"
    />

    <div class="payment-content">
      <!-- 订单信息 -->
      <div class="order-info">
        <div class="order-title">订单信息</div>
        <div class="order-detail">
          <div class="order-row">
            <span>订单号：</span>
            <span>{{ orderData.orderId }}</span>
          </div>
          <div class="order-row">
            <span>商品数量：</span>
            <span>{{ orderData.items?.length || 0 }}件</span>
          </div>
          <div class="order-row">
            <span>支付金额：</span>
            <span class="amount">¥{{ orderData.amount?.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-methods">
        <div class="method-title">选择支付方式</div>
        <div class="method-item active">
          <div class="method-left">
            <van-icon name="gold-coin-o" class="method-icon" />
            <span>支付宝</span>
          </div>
          <van-icon name="success" color="#52c41a" />
        </div>
      </div>

      <!-- 二维码显示区域 -->
      <div v-if="showQrCode" class="qr-code-section">
        <div class="qr-title">请使用支付宝扫码支付</div>
        <div class="qr-code-container">
          <img :src="qrCodeUrl" alt="支付二维码" class="qr-code" />
        </div>
        <div class="qr-tips">
          <p>• 请在5分钟内完成支付</p>
          <p>• 支付完成后请点击下方确认按钮</p>
        </div>
        
        <!-- 添加确认支付按钮 -->
        <van-button 
          type="primary" 
          @click="confirmPayment"
          class="confirm-button"
        >
          我已完成支付
        </van-button>
      </div>

      <!-- 支付状态 -->
      <div v-if="paymentStatus !== 'pending'" class="payment-status">
        <div v-if="paymentStatus === 'processing'" class="status-processing">
          <van-loading type="spinner" size="24px" />
          <span>正在处理支付...</span>
        </div>
        <div v-else-if="paymentStatus === 'success'" class="status-success">
          <van-icon name="success" color="#52c41a" size="32px" />
          <span>支付成功！</span>
        </div>
        <div v-else-if="paymentStatus === 'failed'" class="status-failed">
          <van-icon name="close" color="#f5222d" size="32px" />
          <span>支付失败</span>
        </div>
      </div>
    </div>

    <!-- 底部支付按钮 -->
    <div class="payment-footer">
      <div class="amount-info">
        <span class="amount-label">支付金额</span>
        <span class="amount-value">¥{{ orderData.amount?.toFixed(2) }}</span>
      </div>
      <van-button
        type="primary"
        size="large"
        @click="processPayment"
        :disabled="paymentStatus !== 'pending'"
        class="pay-button"
      >
        {{ paymentStatus === 'pending' ? '立即支付' : 
           paymentStatus === 'processing' ? '支付中...' : 
           paymentStatus === 'success' ? '支付成功' : '重新支付' }}
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.payment-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.payment-content {
  flex: 1;
  padding: 16px;
}

.order-info {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.order-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
}

.order-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.amount {
  color: #ff4444;
  font-weight: bold;
}

.payment-methods {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.method-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
}

.method-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.method-item.active {
  border-color: #1890ff;
  background-color: #f6ffed;
}

.method-left {
  display: flex;
  align-items: center;
}

.method-icon {
  margin-right: 8px;
  font-size: 20px;
}

.qr-code-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  text-align: center;
}

.qr-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.qr-code-container {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.qr-code {
  width: 200px;
  height: 200px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
}

.qr-tips {
  text-align: left;
  color: #666;
  font-size: 12px;
}

.qr-tips p {
  margin: 4px 0;
}

.payment-status {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
}

.status-processing,
.status-success,
.status-failed {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.payment-footer {
  background: white;
  padding: 16px;
  border-top: 1px solid #e8e8e8;
}

.amount-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.amount-value {
  color: #ff4444;
  font-size: 18px;
  font-weight: bold;
}

.pay-button {
  width: 100%;
}
</style>